// import { toRaw } from 'vue';
import { defineStore } from 'pinia'
import storage from '@/utils/storage/index'
import api from '@api/index'

// 菜单栏折叠变量
export const userUserInfoStore = defineStore('userInfoStore', {
  state: () => ({
    userInfo: null, // 用户惜
    token: null
  }),
  actions: {
    // 登入
    login(data) {
      return new Promise((resolve, reject) => {
        api.login.login(data).then(res => {
          const token = res?.token
          if (token) {
            this.token = token
            storage.set('token', token)
            return this.getUserInfo()
          } else {
            return reject('未获取到token')
          }
        })
          .then((userInfo) => {
            resolve({
              token: this.token,
              userInfo,
              // userInfo: toRaw(this.userInfo)
            })
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        api.user.getUserInfo()
          .then(res => {
            this.userInfo = res
            storage.set('userInfo', JSON.stringify(res))
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    // 登出
    async logOut() {
      const userInfo = storage.get('userInfo')
      console.log('userInfo=====>', userInfo)

      userInfo?.id &&
        (await api.login.logOut({
          id: userInfo.id
        }))
      this.userInfo = null
      storage.clear()
    }
  }
})
